<template>
  <div>
    <input type="file" multiple accept="*" v-on:change="addShapefile" placeholder="添加shapefile" ref="fileInput"></input>
    <template>
      <el-dialog :visible.sync="select.show" title="选择名称属性">
        <template>
          <el-table :data="select.properties" border  class="table-container" height="400px">
            <div id="fieldProperties">
              <!-- 循环生成表头列 -->
              <el-table-column
                  v-for="(field, colIndex) in select.fieldName"
                  :key="colIndex"
                  :label="field"
                  :prop="field"
                  :width="select.allSelect === field ? 'auto' : '50px'"
              >
                <template #header>
                  <el-radio-group v-model="select.allSelect" :title="field">
                    <el-radio :label="field"></el-radio>
                  </el-radio-group>

                </template>
                <!-- 单元格内容 -->
                <template #default="scope" style="overflow-x: hidden">
                  <div @click="select.allSelect=field" :title="field">
                    <div v-if="select.allSelect===field">
                      {{ scope.row[field] }}
                    </div>
                    <div v-else>{{ (scope.row[field]) | cut  }}</div>
                  </div>
                </template>
              </el-table-column>
            </div>
          </el-table>
        </template>
        <template #footer>
          <el-button @click="select.show = false">取消</el-button>
          <el-button type="primary" @click="confirmNameSelection">确定</el-button>
        </template>
      </el-dialog>
    </template>
    <el-button @click="clear">清除</el-button>
<!--    <AMapSingleView></AMapSingleView>-->
    <div v-if="features.length>0">
      <AMapView :updateMap="updateMap" :updateCoordsy="updateCoordsy"></AMapView>
      <el-table
          :data="features"
          style="width: 100%;margin-top: 10px"
          border
      >
        <el-table-column
            type="index"
            label="序号"
        ></el-table-column>
        <el-table-column
            label="数据"
            style='overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;'>
          <template v-slot="{$index,row}">
            {{row.mapData.name||"unknow name"}}<span v-if="row.mapData.top">&#9875;</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{$index,row}">
            <el-button  type="danger" @click="deleteMapData(row)" circle icon="el-icon-delete"></el-button>
            <el-button size="mini" @click="moveTo(row)" circle icon="el-icon-location"></el-button>
            <el-button size="mini" @click="upload(row,$index)" circle icon="el-icon-top" v-if="!showUpload($index)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-else>
      <el-tree
          :props="props"
          :load="loadNode"
          lazy
          @check-change="handleCheckChange"
          :data="data"
          :render-content="renderContent"
      >
      </el-tree></div>
  </div>
</template>

<script>
import {mapActions, mapState} from "vuex";
import {reqGetFeatureByFeatureId, reqGetFeatureListTree} from "@/api/feature";
import {requestGetData,  requestIsSuccess} from "@/api/request";
import {Feature} from "@/class/map/Feature"
import {successMessage, warningMessage} from "@/utils/message";
import {getShapeFile} from "@/utils/map";
import {MyMapOpt} from "@/class/map/myMapOpt";
import AMapSingleView from "@/views/map/AMapSingleView.vue";
import {MapData} from "@/class/map/MapData";
import {Polygon, PolygonData} from "@/class/map/Polygon";
import {getRandomColor, getUUID} from "@/utils/utils";
import AMapView from "@/views/map/AMapView.vue";
import {Polyline, PolylineData} from "@/class/map/Polyline";
import {Marker, MarkerData} from "@/class/map/Maker";


export default {
  name: "MapList",
  components: {AMapView, AMapSingleView},
  data() {
    return {
      data: [],
      props: {
        label: 'name',
        children: 'zones'
      },
      //用户添加数据，选择属性
      select:{
        show:false,
        //字段名
        fieldName:null,
        //属性名
        properties:null,
        //全选字段
        allSelect:undefined,
        //添加的数据,临时
        features:null
      },
      map:undefined,
      mapCoordSys:MyMapOpt.MapCoordSys.CJ02,
      features:[],
      featuresIsUpload:[]
    }
  },
  methods: {
    showUpload(index){
      return this.featuresIsUpload[index]||false
    },
    /**
     * 通过id获取行政边界，并添加数据到数据库
     * @param id
     * @returns {Promise<void>}
     */
    async addFeature2MapById(id) {
      this.addFeature2Map(id)
    },
    /**
     * 获取数据并上传
     * @param id
     * @returns {Promise<boolean|void>}
     */
    async addFeature2Map(id) {
      const result = await reqGetFeatureByFeatureId(id);
      if (requestIsSuccess(result)) {
        const data = requestGetData(result);
        var feature = new Feature(data);
        var myMap = feature.getMyMap()
        const flag = await myMap.upload()
        if (flag) {
          successMessage("已保存" + myMap.mapData.name)
        }
      }
    },
    loadNode(node, resolve) {
      if (node.level === 0) {
        reqGetFeatureListTree(node.level + 1, "").then(result => {
          if (requestIsSuccess(result)) {
            const firstLevelList = requestGetData(result);
            const config = []
            for (let i = 0; i < firstLevelList.length; i++) {
              config[i] = {name: firstLevelList[i].featuresName, data: firstLevelList[i]}
            }
            resolve(config);
          }
        })
      } else {
        reqGetFeatureListTree(node.level + 1, node.data.data.id).then(result => {
          if (requestIsSuccess(result)) {
            const featureList = requestGetData(result);
            const config = []
            for (let i = 0; i < featureList.length; i++) {
              const tempData = featureList[i]
              config[i] = {
                name: tempData.name,
                data: tempData
              }
            }
            resolve(config)
          }
        })
      }
    },
    handleCheckChange(data, checked, indeterminate) {
      console.log(data, checked, indeterminate);
    },
    renderContent(h, {node, data, store}) {
      if (node.level === 1)
        return (<span className="custom-tree-node">
            <span>{node.label}</span>
          </span>);
      else
        return (
            <span class="custom-tree-node">
            <span>{node.label}</span>
            <span>
              <el-button size="mini" type="text"
                         on-click={() => this.addFeature2MapById(data.data.featureId)}>添加</el-button>
            </span>
          </span>);
    },
    updateMap(map) {
      this.map = map
    },
    updateCoordsy(){
      this.mapCoordSys=coordsy
    },

    addShapefile(event){
      getShapeFile(event).then(features => {
        if(features){
          if(!features[0].properties){
            warningMessage("文档属性表有误")
            this.select.properties=features.map(()=>{
              return {"random":getUUID()}
            })
            this.select.fieldName=["random"]
          }else{
            this.select.properties=features.map(feature=>feature.properties)
            this.select.fieldName=Object.keys(features[0].properties)
          }
          this.select.show=true;
          this.select.features=features
        }else{
          console.log("未选择对象")
          return;
        }
      })
    },
    confirmNameSelection(){
      this.select.show=false;
      //default coordsys
      const coordsys = MyMapOpt.MapCoordSys.GPS
      this.features.splice(0,this.features.length)
      for (let i = 0; i < this.select.features.length; i++) {
        let feature = this.select.features[i];
        const{geometry:{type,coordinates},properties}=feature
        let path = coordinates
        while(path.length === 1){
          path=path[0]
        }
        let name = this.select.properties[i][this.select.allSelect]||getUUID()
        let item = null;
        if(name) {
          let mapData = undefined
          switch (type) {
            case MyMapOpt.MapType.Polygon:
            case "MultiPolygon"://todo 取消字符串
              const polygon = new Polygon({
                id: undefined,//自动生成uuid，防止重复上传，id一致
                path,
              });
              mapData = new MapData({
                id: getUUID(),//自动生成uuid，防止重复上传，id一致
                type: MyMapOpt.MapType.Polygon,
                name,
                coordsys,
              })
              item = new PolygonData({mapData, polygon});
              break;
            case  MyMapOpt.MapType.Polyline:
            case  "MultiLineString":
            case  "LineString":
              const polyline = new Polyline({
                id: undefined,
                path
              });
              mapData = new MapData({
                id: getUUID(),//自动生成uuid，防止重复上传，id一致
                type: MyMapOpt.MapType.Polyline,
                name,
                coordsys,
              })
              item = new PolylineData({mapData,polyline});
              break;
            case MyMapOpt.MapType.Marker:
              const marker = new Marker({
                id: undefined,
                position:path,
              });
              mapData = new MapData({
                id: getUUID(),//自动生成uuid，防止重复上传，id一致
                type: MyMapOpt.MapType.Marker,
                name,
                coordsys,
              });
              item = new MarkerData({mapData,marker})
          }
          if(item) {
            this.features.push(item);
            this.featuresIsUpload.push(false);
          }else{
            console.log("地图要素创建失败:",feature,"类型：",type)
          }
          // this.addFeature(data)
        }
      }
    },
    async upload(item) {
      let flag = await item.upload();
      if (flag) {
        let index = this.features.findIndex(feature => {
          return feature.mapData.id === item.mapData.id
        })
        this.featuresIsUpload.splice(index, 1, true)
        item.getDateInMap(this.map).clearEvents("click");
        successMessage("添加成功")
      }
    },
    /**
     * 清除添加的地图数据
     */
    clear(){
      this.$refs.fileInput.value = '';
      this.features.splice(0,this.features.length)
    },
    deleteMapData(row){
      this.deleteFeature(row)
    },
    moveTo(row){
      row.blinkData(this.map)
      row.moveTo(this.map)
    },
    ...mapActions('mapList',{
      addFeature:"addFeature",
      deleteFeature:"deleteFeature",
    }),
  },
  filters:{
    cut(value){
      if(value)
        return value.toString().substring(0,4)
    }
  },
  watch:{
    features(newVal){
      const intervalId = setInterval(() => {
        if (this.map!== undefined) {
          clearInterval(intervalId);

          const dataInMap = this.map.getAllOverlays();
          dataInMap.forEach(data=>{
            let flag = newVal.findIndex(item=>{
              return item.mapData.id === data.getExtData().id
            })
            if(flag===-1){
              this.map.remove(data)
            }
          })
          newVal.forEach(item=>{
            const flag = item.getDateInMap(this.map)
            if(!flag) {
              const feature = item.addToMap(this.map, item.mapData.coordsys)
              feature.on('click', () => {
                this.upload(item)
              })
            }
          })
        }
      }, 100);



    }
  }
}
</script>

<style scoped>
  .table-container {
    //height: 400px; /* 设置表格容器的固定高度 */
    overflow-y: auto; /* 允许垂直滚动 */
    overflow-x: visible; /* 允许垂直滚动 */
  }
  /deep/ div.el-table__body-wrapper{
    overflow: visible;
  }
  /deep/ div.el-table__header-wrapper{
    overflow: visible;
  }
</style>